import { useState } from "react";
import { Question } from "../interface";

interface QuestionItemProps {
    item: Question
    index: number
}
export const QuestionItem = (props: QuestionItemProps) => {
    const { item, index } = props
    const { question, radios, muti } = item
    const [checked, setChecked] = useState(new Set<number>())
    const onCheckedChange = (index1: number) => {
        const newChecked = new Set(checked)
        if (checked.has(index1)) {
            newChecked.delete(index1)
        } else {
            if (muti) {
                newChecked.add(index1)
            } else {
                newChecked.clear()
                newChecked.add(index1)
            }
        }
        setChecked(newChecked)
    }
    return (
        <li className="p-2 list-decimal">
            <h2>{
                muti && <small className="text-sm text-gray-500 border border-gray-500 rounded-md px-1 mr-1 hidden print:inline-block">多选</small>
            }{question} <em className="inline-block">(<span className={`text-center inline-block ${muti ? 'w-14' : 'w-6'}`}>{
                [...checked].sort().map(item => ['A', 'B', 'C', 'D'][item]).join('')
            }</span>)</em></h2>
            <div className="overflow-hidden">
                {radios.map((radio, index1) => (
                    <label key={index1} className="float-left flex xl:w-1/4 md:w-1/2 sm:w-full print:w-1/2">
                        <input type={muti ? "checkbox" : "radio"} name={`question-${index}`}
                            checked={checked.has(index1)}
                            onChange={() => onCheckedChange(index1)}
                            className="float-left h-6 mr-1 print:hidden" />
                        <em className="float-left mr-1 hidden print:block">{['A', 'B', 'C', 'D'][index1]}.</em>
                        <span className="inline-block break-all">{radio}</span>
                    </label>
                ))}
            </div>
        </li>
    )
}
